<template>
  <el-dialog
    :modelValue="visiable"
    title="编辑项目"
    width="500"
    @close="$emit('closed')"
  >
    <el-form
      :model="editProj"
      :rules="formRules"
      label-width="80px"
      :inline="false"
      class="mt-6"
      ref="ruleFormRef"
    >
      <el-form-item label="项目名称" prop="name">
        <el-input v-model="editProj.name" placeholder="请输入项目名称" />
      </el-form-item>

      <el-form-item label="项目简称" prop="shortName">
        <el-input v-model="editProj.shortName" placeholder="请输入项目简称" />
      </el-form-item>

      <el-form-item label="电压等级" prop="dianya">
        <el-select v-model="editProj.dianya" placeholder="请选择电压等级">
          <el-option label="220千伏" value="220千伏" />
          <el-option label="500千伏" value="500千伏" />
          <el-option label="750千伏" value="750千伏" />
          <el-option label="±800千伏" value="±800千伏" />
          <el-option label="1000千伏" value="1000千伏" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          立即修改
        </el-button>
        <el-button @click="$emit('closed')">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup lang="ts">
import useProjStore from "@/states/useProjStore";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import { ref } from "vue";

const { visiable, editProj } = defineProps<{
  visiable: Boolean;
  editProj: ProjDataInter;
}>();
const emit = defineEmits(["closed"]);

const ruleFormRef = ref();

const formRules = ref<FormRules<ProjDataInter>>({
  name: [{ required: true, message: "项目名称不能为空", trigger: "blur" }],
  shortName: [
    { required: true, message: "项目简称不能为空", trigger: "blur" },
    { min: 3, max: 5, message: "长度必须为3-5位之间", trigger: "blur" },
  ],
  dianya: [{ required: true, message: "电压等级不能为空" }],
});

const projState = useProjStore();

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      await projState.update(editProj.id!, editProj);
      ElMessage({
        type: "success",
        message: "成功修改",
      });
      emit("closed");
    } else {
      console.log("error", fields);
    }
  });
};
</script>

<style></style>
